package com.basic.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.basic.auth.controller.req.AuthRoleMemberReqForm;
import com.basic.auth.dao.mapper.AuthRoleFuncMapper;
import com.basic.auth.dao.mapper.AuthRoleMemberExMapper;
import com.basic.auth.dao.mapper.AuthRoleMemberMapper;
import com.basic.auth.dao.model.*;
import com.basic.auth.domain.AuthFuncBo;
import com.basic.auth.domain.AuthRoleMemberBo;
import com.basic.auth.domain.AuthUserFuncBo;
import com.basic.auth.service.AuthFuncService;
import com.basic.auth.service.AuthRoleMemberService;
import com.basic.auth.service.AuthUserFuncService;
import com.basic.common.bean.BeanCopierDsUtil;
import com.basic.common.bean.BeanCopyDsUtil;
import com.basic.common.constant.CommonDsConstant;
import com.basic.common.exception.business.DataException;
import com.basic.common.result.WebResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户角色管理
 *
 * @author 
 * @version 1.0
 * @Date 2018/8/14 9:47
 */
@Service
public class AuthRoleMemberServiceImpl implements AuthRoleMemberService {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private AuthRoleMemberExMapper authRoleMemberExMapper;
    @Autowired
    private AuthRoleMemberMapper authRoleMemberMapper;
    @Autowired
    private AuthUserFuncService authUserFuncService;
    @Autowired
    private AuthRoleFuncMapper authRoleFuncMapper;
    @Autowired
    private AuthFuncService authFuncService;

    /**
     * 查询用户角色关系集合
     *
     * @param roleMemberBo
     * @return java.util.List<com.nxin.middle.basic.auth.domain.AuthRoleMemberBo>
     * @author 
     * @date 15:27 2018/8/21
     **/
    @Override
    public List<AuthRoleMemberBo> selListBySysIdSubSysId(AuthRoleMemberBo roleMemberBo) {
        log.info("==========查询用户角色关系集合条件==========" + roleMemberBo);
        if (roleMemberBo == null
                || roleMemberBo.getSystemId() == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        List<AuthRoleMemberBo> roleMemberBoList = authRoleMemberExMapper.selRoleMemberList(roleMemberBo);
        log.info("==========查询查询用户角色关系返回集合==========" + JSON.toJSONString(roleMemberBoList));
        return roleMemberBoList;
    }

    @Override
    public List<AuthRoleMemberBo> selRoleMemberPageList(AuthRoleMemberBo roleMemberBo) {
        log.info("==========查询条件==========" + roleMemberBo);
        if (roleMemberBo == null
                || roleMemberBo.getSystemId() == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        List<AuthRoleMemberBo> roleMemberBoList = authRoleMemberExMapper.selRoleMemberPageList(roleMemberBo);

        return roleMemberBoList;
    }

    /**
     * 根据条件删除用户关系
     *
     * @param roleMemberBo
     * @return int
     * @author 
     * @date 9:45 2018/8/22
     **/
    @Override
    public int delRoleMemberByParam(AuthRoleMemberBo roleMemberBo) {
        if (roleMemberBo == null) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        AuthRoleMemberExample example = new AuthRoleMemberExample();
        AuthRoleMemberExample.Criteria criteria = example.createCriteria();
        criteria.andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED_VAL);
        if (Strings.isNotBlank(roleMemberBo.getRoleCode())) {
            criteria.andRoleCodeEqualTo(roleMemberBo.getRoleCode());
        }
        if (roleMemberBo.getBoId() != null) {
            criteria.andBoIdEqualTo(roleMemberBo.getBoId());
        }
        if (Strings.isNotBlank(roleMemberBo.getBusId())) {
            criteria.andBusIdEqualTo(roleMemberBo.getBusId());
        }
        if (Strings.isNotBlank(roleMemberBo.getBusType())) {
            criteria.andBusTypeEqualTo(roleMemberBo.getBusType());
        }
        if (roleMemberBo.getSystemId() != null) {
            criteria.andSystemIdEqualTo(roleMemberBo.getSystemId());
        }
        if (roleMemberBo.getSubSystemId() != null) {
            criteria.andSubSystemIdEqualTo(roleMemberBo.getSubSystemId());
        }
        if(roleMemberBo.getBoIdList() !=null && roleMemberBo.getBoIdList().size()>0){
            criteria.andBoIdIn(roleMemberBo.getBoIdList());
        }
        AuthRoleMember member = new AuthRoleMember();
        member.setIsEnabled(CommonDsConstant.IS_NOT_ENABLED_VAL);
        int result = authRoleMemberMapper.updateByExampleSelective(member, example);
        if (result <= 0) {
//            throw new ServerServiceException(Errors.SYSTEM_DELETE_ERROR);
        }
        // 判断是否关联删除用户功能关系
        if (CommonDsConstant.DEFAULT_INT_NO.equals(roleMemberBo.getIsRelationFunc())) {
            return result;
        }
        /* 条件：用户id，业务类型，业务id，系统id，子系统id */
        AuthUserFunc userFunc = new AuthUserFunc();
        if (roleMemberBo.getBoId() != null) {
            userFunc.setBoId(roleMemberBo.getBoId());
        }
        if (Strings.isNotBlank(roleMemberBo.getBusType())) {
            userFunc.setBusType(roleMemberBo.getBusType());
        }
        if (Strings.isNotBlank(roleMemberBo.getBusId())) {
            userFunc.setBusId(roleMemberBo.getBusId());
        }
        if (roleMemberBo.getSystemId() != null) {
            userFunc.setSystemId(roleMemberBo.getSystemId());
        }
        if (roleMemberBo.getSubSystemId() != null) {
            userFunc.setSubSystemId(roleMemberBo.getSubSystemId());
        }
        authUserFuncService.delUserFuncByParam(userFunc);
        return result;
    }

    /**
     * 添加用户角色
     *
     * @param roleMemberBo
     * @return void
     * @author 
     * @date 18:40 2018/8/14
     **/
    @Override
    public void addRoleMember(AuthRoleMemberBo roleMemberBo) {
        log.info("==========添加内容==========" + roleMemberBo);
        if (roleMemberBo == null
                || roleMemberBo.getBoId() == null
                || Strings.isBlank(roleMemberBo.getRoleCodes())
                || Strings.isBlank(roleMemberBo.getBusId())
                || Strings.isBlank(roleMemberBo.getBusType())) {
//            throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
        }
        Short systemId = roleMemberBo.getSystemId();
        AuthRoleMemberBo param = new AuthRoleMemberBo();
        param.setBusId(roleMemberBo.getBusId());
        param.setBusType(roleMemberBo.getBusType());
        param.setBoId(roleMemberBo.getBoId());
        if (systemId != null) {
            param.setSystemId(systemId);
        }
        if (roleMemberBo.getSubSystemId() != null){
            param.setSubSystemId(roleMemberBo.getSubSystemId());
        }
        log.info("作废历史用户角色关系");
        if(roleMemberBo.getIsRelationFunc() != null){
            param.setIsRelationFunc(roleMemberBo.getIsRelationFunc());
        }
        List<AuthRoleMemberBo> roleMemberBoList = selListBySysIdSubSysId(param);
        if(CollectionUtils.isNotEmpty(roleMemberBoList)){
            delRoleMemberByParam(param);
        }
        AuthRoleMember roleMember = BeanCopierDsUtil.copyProperties(roleMemberBo, AuthRoleMember.class);
        String[] roleCodes = roleMemberBo.getRoleCodes().split(CommonDsConstant.DELIMITER_SG_ZY);
        for (String roleCode : roleCodes) {
            roleMember.setRoleCode(roleCode);
            int result = authRoleMemberMapper.insertSelective(roleMember);
            if (result <= 0) {
//                throw new ServerServiceException(Errors.SYSTEM_INSERT_ERROR);
            }
        }
        String funcIds = roleMemberBo.getFuncIds();
        if (Strings.isNotBlank(funcIds)) {
            AuthUserFuncBo userFuncBo = new AuthUserFuncBo();
            /* 属性： 系统id 子系统id  功能id 用户id 业务类型 业务id*/
            BeanCopyDsUtil.copyProperties(roleMemberBo, userFuncBo);
            authUserFuncService.addUserFuncs(userFuncBo);
        }
    }

/**
 * 批量添加角色成员
 *
 * @param roleMemberBo 角色成员信息对象，包含角色编码、关联人员ID列表等信息
 * @return WebResult 返回操作结果，包括消息和状态码
 */
@Override
public WebResult addBatchRoleMember(AuthRoleMemberBo roleMemberBo) {
    // 初始化WebResult对象
    WebResult result = new WebResult();

    // 检查关联人员ID列表是否为空
    if(roleMemberBo.getBoIdList() == null || roleMemberBo.getBoIdList().size()==0){
        // 设置错误消息和状态码
        result.setMsg("关联人员为空");
        result.setCode("-1");
        // 记录日志
        log.info("-------BoIdList is Empty--------");
        // 返回结果
        return result;
    }

    // 检查角色编码是否为空
    if(Strings.isBlank(roleMemberBo.getRoleCodes())){
        // 设置错误消息和状态码
        result.setMsg("关联人员编码为空");
        result.setCode("-1");
        // 记录日志
        log.info("-------RoleCode is Empty--------");
        // 返回结果
        return result;
    }

    // 删除已有的角色成员关联，以便重新添加
//    delRoleMemberByParam(roleMemberBo);
    for (String roleCode : roleMemberBo.getRoleCodes().split(CommonDsConstant.DELIMITER_SG_ZY)){
        // 获取关联人员ID列表
        List<String> boIdList = roleMemberBo.getBoIdList();

        // 遍历人员ID列表，为每个ID创建角色成员关联
        for (String boId : boIdList) {

            //查询当前对应关系是否存在
            AuthRoleMemberExample example = new AuthRoleMemberExample();
            AuthRoleMemberExample.Criteria criteria = example.createCriteria();
            criteria.andBoIdEqualTo(boId);
            criteria.andRoleCodeEqualTo(roleCode);
            List<AuthRoleMember> authRoleMembers = authRoleMemberMapper.selectByExample(example);
            if (CollectionUtils.isNotEmpty(authRoleMembers)) {
                // 存在则跳过
                continue;
            }

            AuthRoleMember roleMember = new AuthRoleMember();
            // 设置当前人员的ID
            roleMember.setBoId(boId);
            // 设置当前角色的编码
            roleMember.setRoleCode(roleCode);
            // 设置业务ID为人员ID
            roleMember.setBusId(boId);
            // 设置业务类型为成员
            roleMember.setBusType("MEMBER");
            // 设置系统ID为10
            roleMember.setSystemId((short)10);
            // 设置创建时间为当前时间
            roleMember.setCreateTime(new Date());
            // 设置子系统ID为6
            roleMember.setSubSystemId((short)6);

            // 插入角色成员记录到数据库
            int t = authRoleMemberMapper.insertSelective(roleMember);
            // 如果插入失败，暂不处理异常
            if (t <= 0) {
//            throw new ServerServiceException(Errors.SYSTEM_INSERT_ERROR);
            }
        }

    }

    // 将AuthRoleMemberBo对象转换为AuthRoleMember对象
//    AuthRoleMember roleMember = BeanCopierDsUtil.copyProperties(roleMemberBo, AuthRoleMember.class);



    // 设置成功消息和状态码
    result.setMsg("关联角色人员成功");
    result.setCode("0");
    // 返回结果
    return result;
}


    @Override
    public List<AuthRoleMemberBo> selectByCode(AuthRoleMemberBo roleMemberBo) {
        AuthRoleMemberExample example=new AuthRoleMemberExample();
        example.createCriteria()
                .andSystemIdEqualTo(roleMemberBo.getSystemId())
                .andSubSystemIdEqualTo(roleMemberBo.getSubSystemId())
                .andRoleCodeEqualTo(roleMemberBo.getRoleCodes())
                .andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED_VAL);
        List<AuthRoleMember> authRoleMembers = authRoleMemberMapper.selectByExample(example);
        List<AuthRoleMemberBo> authRoleMemberBos=new ArrayList<>();
        if (CollectionUtils.isNotEmpty(authRoleMembers)){
           authRoleMemberBos = BeanCopierDsUtil.copyPropertiesOfList(authRoleMembers, AuthRoleMemberBo.class);
        }
        return authRoleMemberBos;
    }

    /**
     * 判断用户角色权限
     *
     * @param roleMemberBo
     * @return com.nxin.etpojar.common.result.WebResult<java.lang.Boolean>
     * @author 
     * @since 2019/10/15 11:19
     */
    @Override
    public WebResult<Boolean> judgeUserFuncByRoleAndCode(AuthRoleMemberBo roleMemberBo) {
        log.info("==========查询权限==========" + roleMemberBo);
            if(roleMemberBo == null || roleMemberBo.getBoId() == null){
//                throw new ValidationException(Errors.SYSTEM_REQUEST_PARAM_ERROR);
            }
        List<AuthRoleMemberBo> authRoleMemberBos = selectByCode(roleMemberBo);
        if(CollectionUtils.isEmpty(authRoleMemberBos)){
            return WebResult.success(false);
        }
        List<String> roleList = new ArrayList<>();
        for (AuthRoleMember authRoleMember : authRoleMemberBos) {
            roleList.add(authRoleMember.getRoleCode());
        }
        AuthRoleFuncExample example1 = new AuthRoleFuncExample();
        AuthRoleFuncExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andRoleCodeIn(roleList);
        criteria1.andSystemIdEqualTo(roleMemberBo.getSystemId());
        criteria1.andIsEnabledEqualTo(CommonDsConstant.IS_ENABLED_VAL);
        example1.setOrderByClause("func_id asc");
        List<AuthRoleFunc> authRoleFuncs = authRoleFuncMapper.selectByExample(example1);
        log.info("==========查询到角色{}" ,authRoleFuncs);
        if (CollectionUtils.isEmpty(authRoleFuncs)) {
            return WebResult.success(false);
        }
        List<Long> funcIdList = new ArrayList<>();
        for (AuthRoleFunc authRoleFunc : authRoleFuncs) {
            funcIdList.add(authRoleFunc.getFuncId());
        }
        AuthFuncBo funcBo = new AuthFuncBo();
        funcBo.setFuncIdList(funcIdList);
        funcBo.setSystemId(roleMemberBo.getSystemId());
        List<AuthFunc> authFuncs = authFuncService.selFuncListByParam(funcBo);
        log.info("==========查询到角色权限{}" ,authFuncs);
        if(CollectionUtils.isEmpty(authFuncs)){
            return WebResult.success(false);
        }
        for (AuthFunc authFunc : authFuncs) {
            if(authFunc.getCode().equals(roleMemberBo.getCode())){
                return WebResult.success(true);
            }
        }
        return WebResult.success(false);

    }

    @Transactional
    @Override
    public WebResult confirmAssociation(AuthRoleMemberBo roleMemberBo) {
        // 判断数据是否符合要求
        if (StringUtils.isNotBlank(roleMemberBo.getRoleCode())) {
            // 关联的数据进行数据假删
            AuthRoleMember authRoleMember = new AuthRoleMemberBo();
            authRoleMember.setIsEnabled(CommonDsConstant.IS_NOT_ENABLED);
            AuthRoleMemberExample example = new AuthRoleMemberExample();
            AuthRoleMemberExample.Criteria criteria = example.createCriteria();
            criteria.andRoleCodeEqualTo(roleMemberBo.getRoleCode());
            authRoleMemberMapper.updateByExampleSelective(authRoleMember, example);
            //将绑定的数据进行批量数据添加
            if (!CollectionUtils.isEmpty(roleMemberBo.getBoIdList())) {
                authRoleMemberExMapper.insertBatchRoleMembers(roleMemberBo);
            }
            return WebResult.success();
        }
        throw new DataException("确认关系失败");
    }

    @Override
    public int countUserByRoleCode(String roleCode) {
        AuthRoleMemberExample example = new AuthRoleMemberExample();
        AuthRoleMemberExample.Criteria criteria = example.createCriteria();
        criteria.andRoleCodeEqualTo(roleCode);
        List<AuthRoleMember> authRoleMembers = authRoleMemberMapper.selectByExample(example);
        return authRoleMembers.size();
    }

    @Override
    public WebResult cancelAssociation(AuthRoleMemberReqForm roleMemberReqForm) {
        int i = 0;
        for (String roleCode : roleMemberReqForm.getRoleCodeList()) {
            AuthRoleMemberExample example = new AuthRoleMemberExample();
            AuthRoleMemberExample.Criteria criteria = example.createCriteria();
            criteria.andRoleCodeEqualTo(roleCode);
            criteria.andBoIdEqualTo(roleMemberReqForm.getBoId()+"");
            int j = authRoleMemberMapper.deleteByExample(example);
            i += j;
        }

        return WebResult.success("取消关联成功,"+i+"条数据被删除");
    }

    @Override
    public List<String> selRoleListByBoId(String boId) {
        List<String> roleList = authRoleMemberExMapper.selRoleListByBoId(boId);
        return roleList;
    }
}
